package com.wbihua.metrics.metric;

import com.wbihua.common.metrics.manager.MetricManager;
import com.wbihua.common.metrics.metric.EventMeterPrometheusHistogram;
import com.wbihua.common.metrics.type.EventPrometheusHistogramType;
import io.micrometer.prometheus.PrometheusMeterRegistry;
import io.prometheus.client.CollectorRegistry;
import io.prometheus.client.Histogram;

import java.util.function.Consumer;
import java.util.function.Supplier;

public class PrometheusMetricHistogram implements EventMeterPrometheusHistogram {
    private final EventPrometheusHistogramType counterType;

    private Histogram histogram;

    public PrometheusMetricHistogram(EventPrometheusHistogramType counterType) {
        this.counterType = counterType;
    }
    @Override
    public void registry(MetricManager metricManager) {
        CollectorRegistry prometheusRegistry =((PrometheusMeterRegistry)metricManager.getMetricRegistry()).getPrometheusRegistry();
        histogram = Histogram.build()
                .name(counterType.getName())
                .labelNames(counterType.getLabelNames())
                .help(counterType.getHelp())
                .register(prometheusRegistry);
    }

    @Override
    public <T> T getMeter() {
        return (T)this.histogram.labels();
    }

    @Override
    public <T> T getMeter(String... tagValues) {
        return (T)this.histogram.labels(tagValues);
    }

    @Override
    public EventPrometheusHistogramType getCounterType() {
        return this.counterType;
    }

    @Override
    public void startTimer(Consumer<Object> saveTimer, String... labelValues) {
        Histogram.Timer timer = histogram.labels(labelValues).startTimer();
        saveTimer.accept(timer);
    }

    @Override
    public void observeDuration(Supplier<Object> timerSupplier) {
        Histogram.Timer timer = (Histogram.Timer)timerSupplier.get();
        timer.observeDuration();
    }
}
